<template>
	<div id="speak_test_vue" class="speak-content word-book-content"
		style="background: rgb(245, 247, 250); padding-top: 20px;">
		<div class="tooltip" :style="{ left:state.menuPosition.x+'px',top:state.menuPosition.y+'px' }"
			@click.stop="addtopWord" v-if="state.wordTxt">加入单词本</div>
		<div class="t_a1">
			<div class="course-a"><span>首页 &gt; 口语题库 &gt; <span id="singleName">{{ state.realData.title }}</span></span>
			</div>
			<div id="speak_middle_content">
				<div id="speak_left" class="flex" style="width: 1100px;">
					<div id="myDiv" class="speak_topic_modelList">
						<div class="flex speak_tb">
							<div class="speak_tb1" style="">PART {{ state.partIndex }}</div>
							<div class="speak_tb3">{{ state.realData.title }}</div>
						</div>
						<div class="speak-content2" style="height: 603px; position: relative;">
							<template v-if="state.list.length">
								<template v-for="(item,index) in state.list[state.moduleIndex].examList" :key="index">
									<div class="speak-a">
										<div class="speak_topic flex_item" @click="examChange(index)">
											{{index+1}}.<div v-html="item.contentText"></div>
											<img src="../assets/close(1).png" style="margin-left: auto; display: none;">
											<img src="../assets/open.png" style="margin-left: auto;">
										</div> <input hidden="hidden" id="url">
										<div class="speak_content" v-show="index == state.examIndex">
											<div class="flex speakss">
												<div class="sp-title" @click="changeVersion(1)"
													:class="{'sp-title-active1':state.selectVersion == 1}">基础版
													<div></div>
												</div>
												<div class="sp-title" @click="changeVersion(2)"
													:class="{'sp-title-active1':state.selectVersion == 2}">进阶版
													<div></div>
												</div>
											</div>
											<span>
												<div class="speak_content_text" v-html="item.analysis"
													v-if="state.selectVersion == 1"></div>
												<div class="speak_content_text" v-html="item.analysis1"
													v-if="state.selectVersion == 2"></div>
											</span> <!---->
										</div>
										<div class="speak_test1" v-show="index == state.examIndex">
											<div class="flex speakss">
												<div class="sp-title sp-title2 sp-title-active1">答题笔记</div>
												<button class="sp-save-btn" @click="saveTxt()">保存笔记</button>
											</div>
											<div class="speak_test_text">
												<textarea id="tkContent_3462"
													placeholder="在此输入答题笔记内容。请点击左上方按钮保存笔记内容，否则笔记内容会丢失" class="sp_text"
													v-model="item.userAnswer"></textarea>
											</div>
											<div class="flex_centen">
												<div class="speak_recordingLeft" style="width: auto;">
													<div class="flex_centen" v-show="state.recStatus == 0">
														<div class="audio-left1" style="width: 55px;"><img
																@click="recStart()" src="../assets/recordingVoice.png"
																class="cursor speak-c" style="width: 44px;">
															<div style="width: 55px;">开始录音</div>
														</div>
													</div>
													<div class="" v-show="state.recStatus == 1">
														<div class="flex"><img src="../assets/stopRecord.png"
																@click="recStop()" class="cursor">&nbsp;&nbsp;
															<img src="../assets/recording.gif">
														</div>
														<div class="flex" style="margin-top: 10px;">
															<div class="flex_item"
																style="margin-right: 143px; cursor: pointer; flex: 1 1 0%;">
																结束录音
															</div>
															<div class="flex" v-show="state.timeStopAudio>0">
																<div class="flex_item">倒计时&nbsp;</div>
																<div class="flex_item" style="color: rgb(250, 84, 56);">
																	{{state.timeStopAudio}}s
																</div>
															</div>
															<div class="flex_item" v-show="state.timeStopAudio<0"
																style="color: rgb(250, 84, 56);">
																已超时
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</template>
							</template>
						</div>
						<div class="speak_bottom">
							<audio id="audio" style="width: 100%;" controls="controls" loop="loop"
								:src="'http://ielts.tuyaedu.com/boot/sys/common/static/'+ state.videoPath"></audio>
						</div>
					</div>
				</div>
				<div id="speak_right">
					<AsidePart></AsidePart>
				</div>
			</div>
		</div>
	</div>
</template>
<script setup>
	import AsidePart from "./asidePart.vue"
	let Recorder = window.Recorder
	import {
		reactive,
		getCurrentInstance,
		onMounted
	} from 'vue'
	import {
		useRouter,
		useRoute
	} from 'vue-router'
	const router = useRouter()
	const route = useRoute()
	const state = reactive({
		realData: {},
		list: [],
		moduleIndex: 0,
		examIndex: 0,
		audioStatus: 0,
		fyAudioIndex: -1, //考生示范播放录音坐标
		recordAudioStatus: [0, 0], //播放状态  0:未开始  1:进行中
		rec: null,
		recBlob: null,
		partType: 1,
		recordIndex: 0,
		timeAudio: 0, //录音时长
		recStatus: 0, //0:未录音  1:录音中  2:录音完成
		timeStopAudio: 180, //录音自动停止时间
		csInterval: null,
		gradeImgShow: false, //解析图片是否显示
		duration: 0, //当前录音长度
		saveThink: false,
		timeNum: 10,
		timeInterval: null,
		selectVersion: 1,
		speakTxt: '',
		answerList: [],
		videoPath: '',
		wordTxt: '',
		menuPosition: {},
		partIndex: ''
	})

	const {
		proxy
	} = getCurrentInstance()

	state.partIndex = Number(route.query.partIndex) + 1

	document.addEventListener('contextmenu', function(event) {
		event.preventDefault(); // 阻止默认菜单
		state.menuPosition = event
		let txt = mouseSelectText()
		state.wordTxt = txt
	});

	document.addEventListener('click', (e) => {
		state.wordTxt = ''
	});

	function mouseSelectText() {
		return window.getSelection().toString();
	}

	function addtopWord() {
		proxy.$http.post('/boot/user/wordBook/add', {
			word: state.wordTxt
		}).then(res => {
			if (res.data.success) {
				alert(res.data.result)
				state.wordTxt = ''
			}
		})
	}


	const moduleChange = (index) => {
		state.moduleIndex = index
	}
	const getPracticeList = () => {
		proxy.$http.get('/boot/api/questions/paper/queryByName?name=' + route.query.name).then(res => {
			if (res.data.success) {
				state.list = res.data.result
				state.realData = state.list[0]
				if (state.realData.examList.length > 0) {
					state.videoPath = state.realData.examList[state.examIndex].videoPath
				}
				getUserAnswer()
			}
		})
	}

	function getUserAnswer() {
		proxy.$http.get('/boot/user/userPaper/queryByPaperId?paperId=' + state.list[0].id).then(res => {
			if (res.data.success) {
				state.answerList = res.data.result.paperExamList
				if (state.answerList) {
					state.answerList.forEach(function(item1, index1) {
						state.list[0].examList.forEach(function(item2, index2) {
							if (item1.examId == item2.id) {
								state.list[0].examList[index2].userAnswer = state.answerList[
									index1].userAnswer
							}
						})
					})
				}
			}
		})
	}

	function saveTxt() {
		if (confirm('确定是否提交')) {
			proxy.$http.post('/boot/user/userPaper/add', {
				paperId: state.list[0].id,
				paperExamList: [{
					examId: state.list[0].examList[state.examIndex].id,
					userAnswer: state.list[0].examList[state.examIndex].userAnswer
				}],
			}).then(res => {
				if (res.data.success) {
					alert('保存成功')
				}
			})
		}
	}

	const examChange = (index) => {
		state.examIndex = index
		state.videoPath = state.list[0].examList[state.examIndex].videoPath
		state.speakTxt = ''
	}

	const changeVersion = (index) => {
		state.selectVersion = index
	}


	const stopAudio = () => {
		state.audioStatus = 0;
		state.fyAudioIndex = -1;
		state.recordAudioStatus = [0, 0];
		/*this.playTime = [0, 0];
		this.jutWidth = [0, 0];*/
		let audioArray = document.getElementsByTagName("audio");
		for (let i = 0; i < audioArray.length; i++) {
			audioArray[i].pause();
		}
	}

	const isIE = () => {
		if (!!window.ActiveXObject || "ActiveXObject" in window)
			return true;
		else
			return false;
	}


	/**调用open打开录音请求好录音权限**/
	const recOpen = () => { //一般在显示出录音按钮或相关的录音界面时进行此方法调用，后面用户点击开始录音时就能畅通无阻了
		state.rec = null;
		state.recBlob = null;
		var newRec = new Recorder({
			sampleBits: 128, // 采样位数，支持 8 或 16，默认是16
			sampleRate: 44100, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
			numChannels: 1, // 声道，支持 1 或 2， 默认是1
			compiling: false, // 是否边录边转换，默认是false
		});

		if (isIE()) {
			alert("ie不支持麦克风录音，请更换浏览器！");
		} else {
			state.rec = newRec;
		}

		/*let newRec = Recorder({
		    type: "mp3", sampleRate: 16000, bitRate: 16 //mp3格式，指定采样率hz、比特率kbps，其他参数使用默认配置；注意：是数字的参数必须提供数字，不要用字符串；需要使用的type类型，需提前把格式支持文件加载进来，比如使用wav格式需要提前加载wav.js编码引擎
		    , onProcess: function (buffers, powerLevel, bufferDuration, bufferSampleRate, newBufferIdx, asyncEnd) {
		    }
		});
		newRec.open(function () {//打开麦克风授权获得相关资源
		    self.rec = newRec;
		}, function (msg, isUserNotAllow) {//用户拒绝未授权或不支持
		    alert((isUserNotAllow ? "UserNotAllow，" : "") + "打开录音失败：" + msg);
		});

		window.waitDialogClick = function () {
		    alert("打开失败：权限请求被忽略！");
		};*/

	}


	const uploadVideo = () => {
		window.OSSUPLOAD(state.recBlob);
	}

	const getStuOralRecord = () => {
		state.saveThink = false;
		state.timeNum = 10;
		window.clearInterval(state.timeInterval);
		// var juhua = layer.load('Loading…');
		// var _this = this;
		// $.ajax({
		//   cache: false,
		//   type: "GET",
		//   url: jsPath + '/business/ielts/record/queryStuOralRecordByStuId.do',
		//   data: { "stuId": _this.stuId, "topicIssuesId": _this.topicIssuesId, "recordType": _this.answerType },
		//   dataType: "JSON",
		//   async: false,
		//   error: function (request) {
		//     alert('请求失败处理,请联系助教进行处理!');
		//   },
		//   success: function (data) {
		//     let returnData = data.returnData;
		//     _this.playTime = [0, 0];
		//     _this.jutWidth = [0, 0];
		//     _this.recordList = returnData.recordList;
		//     _this.thinkingMap.set(_this.topicIssuesId, returnData.thinking);
		//     _this.gradeImgShow = false;
		//     layer.close(juhua);
		//   }
		// });
	}

	/**结束录音，得到音频文件**/
	const recStop = () => {
		if (!(state.rec)) {
			alert("未打开录音");
			return;
		};
		state.rec.stop();
		var blob = state.rec.getWAVBlob();
		clearInterval(state.csInterval);
		state.gradeImgShow = true;
		state.recStatus = 0;
		state.duration = state.rec.duration.toFixed(0) * 1000;
		state.recBlob = blob;
		// uploadVideo();
		setTimeout(
			function() {
				//self.queryStuDemo();
				state.getStuOralRecord();
				state.getSpokenList();
			},
			7000);

		/* if (!(this.rec && Recorder.IsOpen())) {
		     alert("未打开录音");
		     return;
		 };
		 this.rec.stop(function (blob, duration) {
		     clearInterval(self.csInterval);
		     self.gradeImgShow = true;
		     self.recStatus = 0;
		     self.duration = duration;
		     self.recBlob = blob;
		     self.uploadVideo();
		     setTimeout(
		         function () {
		             self.queryStuDemo();
		             self.getStuOralRecord();
		             self.getSpokenList();
		         },
		         7000);
		 }, function (msg) {
		     callback(msg);
		     console.log("录音失败:" + msg);
		     window.rec.close(); //可以通过stop方法的第3个参数来自动调用close
		     window.rec = null;
		 });*/
	}

	/**开始录音**/
	const recStart = (recordIndex) => { //打开了录音后才能进行start、stop调用
		stopAudio();
		if (isIE()) {
			alert("ie不支持麦克风录音，请更换浏览器！");
		} else {
			if (state.rec) {
				state.rec.stop();
			}
			state.rec.start().then(() => {
				state.recBlob = null;
				let time = 0;
				if (state.partType == 1) {
					time = 30;
				} else if (state.partType == 2) {
					time = 120;
				} else {
					time = 60;
				}
				state.recordIndex = recordIndex;
				state.timeAudio = time;
				state.recStatus = 1;
				state.timeStopAudio = 180;
				state.csInterval = setInterval(() => {
					state.timeAudio = state.timeAudio - 1;
					state.timeStopAudio = state.timeStopAudio - 1;
					if (state.timeStopAudio == 0) {
						clearInterval(state.csInterval);
						state.recStop();
					}
				}, 1000);
				return true;
				// 开始录音
			}, (error) => {
				alert("该浏览器不支持H5录音哦~");
			});
		}
	}

	recOpen()


	getPracticeList()
</script>
<style scoped src="../assets/ielts-speak-test.css"></style>
<style lang="scss" scoped>
	.st-div-screen {
		width: 300px !important;
	}

	.speak_tb3_screen {
		font-size: 18px;
	}

	.speak_topic_screen {
		font-size: 16px;
		width: 100%;
		padding-left: 0px;
	}

	.speak_content_screen {
		width: 100%;
		padding-bottom: 0px;
		margin: -5px 0 -8px 0;
		min-height: 130px;
	}

	.sp-title_screen {
		font-size: 13px;
	}

	.student-voice_screen {
		width: 112px;
		height: 25px;
	}

	.student-voice-time_screen {
		font-size: 11px;
	}

	.student-label_screen {
		margin-bottom: 24px;
	}

	.speak-a_screen {
		width: 620px !important;
		margin-left: 29px;
	}

	.speak_topic_type2_screen {
		width: 55px;
		height: 28px;
		font-size: 13px;
		line-height: 26px;
	}

	.speak_topic_type_screen {
		/*padding-left:150px;*/
	}

	.speakss_screen {
		padding: 15px 0 0 15px;
	}

	.speak_content_text_bottom-screen2 {
		margin: -300px 110px !important;
	}

	/*div{*/
	/*border:1px solid black;*/
	/*}*/
	.searchButton {
		width: 80px;
		height: 100%;
		background-color: #ff4b40;
		color: white;
		border-radius: 0px 10px 10px 0;
	}

	.search {
		/* border: 1px solid; */
		border: 1px solid #f5f7fa;
		/* padding: 2%; */
		height: 40px;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 10px;
		background-color: white;
	}

	div.search input:nth-child(2) {
		border: none;
		outline: none;
	}

	div.search input:nth-child(3) {
		border: none;
	}

	.titlefont {
		display: flex;
		font-size: 3px;
		width: 50px;
		color: #999999;
		display: block;
		text-align: -webkit-right;
	}

	.s1 {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		width: 180px;
		padding-left: 3%;
		display: inline-block;
		text-align: left;
	}

	.s2 {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		width: 80px;
		padding-left: 3%;
		color: #999999 !important;
		display: inline-block;
		text-align: left;
	}

	.top {
		text-align: center;
	}

	.left {
		float: left;
		width: 60px;
	}

	.right {
		float: right;
		width: 60px;
	}

	.bottom {
		clear: both;
		text-align: center;
	}

	.item {
		margin: 4px;
	}

	.left .el-tooltip__popper,
	.right .el-tooltip__popper {
		padding: 8px 10px;
	}

	.speak_content_text_bottom-screen1 {
		margin: -100px 110px -80px 110px;
		width: 400px;
	}

	.topic {}

	.topicin {
		display: flex;
		width: 215px;
		display: flex;
		/* justify-content: center; */
		align-items: center;
		border: 1px solid rgb(232 234 236);
		padding: 1%;
		margin: 0px -1px -1px 0px;
		justify-content: space-between;
	}

	.single-a {
		margin-right: 9%;
	}

	.vd-box {
		margin-top: -206px;
	}

	.vd-box:after {
		content: "";
		position: absolute;
		width: 0;
		height: 0;
		top: 167px;
		left: 34px;
		border-style: solid;
		border-width: 0px;
		border-color: transparent transparent #fff #fff;
		transform: rotate(310deg);
		-webkit-box-shadow: 0 2px 20px 0 #e9e9e9;
		-moz-box-shadow: 0 2px 20px 0 #e9e9e9;
		box-shadow: 0 2px 20px 0 #e9e9e9;
	}

	input[type="checkbox"]:not(.switch):after {
		width: 5.5px !important;
		left: 5.5px !important;
		outline: none !important;
	}

	input[type="checkbox"],
	input[type="radio"] {
		--active-inner: #aaaaaa !important;
		outline: none !important;
	}

	input[type="checkbox"]:checked,
	input[type="radio"]:checked {
		background: #e4ecfa00 !important;
		border-color: #9999 !important;
		outline: none !important;
	}

	input[type="checkbox"],
	input[type="radio"] {
		--input-border: #9999 !important;
		outline: none !important;
	}

	input[type="checkbox"]:not(.switch) {
		border-radius: 3px !important;
		outline: none !important;
	}

	.oral_title {
		color: #2d2c2c;
	}

	.topic-list2 .qt_btn {
		font-size: 15px;
		color: #2d2c2c;
	}

	.qt_btn_active {
		color: #ffffff !important;
	}

	.speak-a {
		width: 876.5px;
	}

	.st-div {
		width: 384px;
	}

	.flex_item_report {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 11px 11px;
		/* border-top: 1px solid #d3d1d1;*/
		border-bottom: 1px solid #d3d1d1;
	}

	.flex_item_report2 {
		background-color: #ddeefd;
		border-top: 1px solid #d3d1d1;
		border-bottom: 0;
	}

	.btn-mock-report {
		padding: 4px 19px;
		background-color: #ddeefd;
		color: #337ab7;
		border: 0;
		border-radius: 6px;
		outline: none !important;
		margin-right: 18px;
	}

	.btn-mock-report2 {
		/* position: absolute;
            margin-left: 63%;
            margin-top: -34px;*/
		white-space: nowrap;
		align-self: center;
		padding: 3px 19px;
		margin-right: 18px;
	}

	.btn-mock-report3 {
		position: absolute;
		margin-left: 64%;
		padding: 5px 13px 3px !important;
		margin-top: -28px;
		font-size: 13px;
	}

	.sp-title2 {
		margin-bottom: 15px;
	}

	.sp-save-btn {
		background-color: #ff4b40;
		border: 0;
		color: white;
		border-radius: 6px;
		height: 26px;
		outline: none !important;
		padding: 0 10px;
	}

	#speak_right div::-webkit-scrollbar {
		width: 4px;
	}

	.speak-answer-btn {
		background: #ff4b40;
		border-radius: 4px;
		border: 0;
		font-family: SourceHanSansCN-Regular;
		font-size: 13px;
		color: #ffffff;
		text-align: center;
		font-weight: 400;
		border: 1px solid rgba(255, 75, 64, 1);
		outline: none;
		/*margin-left: auto;
            margin-right: 2.1%;
            align-self: self-start;*/
	}

	.formulate_btn {
		margin-right: 10px;
		background: #dbe1e9;
		border-radius: 4px;
		border: 0;
		padding: 3px 17px;
		color: white;
		align-self: self-start;
		outline: none !important;
	}

	.formulate_btn3 {
		margin-right: 10px;
		background: #dbe1e9 !important;
		border-radius: 4px;
		border: 0;
		padding: 3px 17px;
		color: white;
		align-self: self-start;
		outline: none !important;
	}

	.formulate_btn2 {
		background-color: #ff4b40;
		color: white;
	}

	.right-navigation-bar-tips {
		width: 5px;
		height: 25px;
		background: #ff4b40;
		border-radius: 0 42px 42px 0;
		border-radius: 0px 42px 42px 0px;
	}

	.right-navigation-bar-title {
		font-family: SourceHanSansCN-Medium;
		font-size: 18px;
		color: #333333;
		letter-spacing: 0;
		font-weight: 600;
		padding-left: 15px;
	}

	.tooltip {
		color: red;
		cursor: pointer;
		opacity: 1;
		padding: 5px 8px;
		background: rgb(255, 239, 238);
		border-radius: 4px;
		box-shadow: rgba(159, 159, 159, 0.5) 0px 1px 5px 0px;
		top: 344px;
		left: 716px;
		position: absolute;
	}
</style>